package com.example.yc;



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;


import java.lang.reflect.Method;




@Configuration

@EnableCaching

public class RedisConfiguration extends CachingConfigurerSupport {
    private RedisTemplate redisTemplate;

    /**
     * key避免乱码
     * @param redisTemplate
     */
    @Autowired(required = false)
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);
        this.redisTemplate = redisTemplate;
    }


    /**
     * 自定义生成key的规则
     * @return
     */
    @Override
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object o, Method method, Object... objects) {
                StringBuilder sb = new StringBuilder();
//                sb.append(o.getClass().getName());
                sb.append(method.getName());
//                for (Object obj : objects) {
//                    // 由于参数可能不同, hashCode肯定不一样, 缓存的key也需要不一样
//                    sb.append(JSON.toJSONString(obj).hashCode());
//                }
                return sb.toString();
            }
        };
    }

    /**
     * 采用RedisCacheManager作为缓存管理器
     * @param redisTemplate
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
        //redisCacheManager.setUsePrefix(true);
        // key缓存的前缀,以conf开头
        //RedisCachePrefix cachePrefix = new DefaultRedisCachePrefix("conf");
        //redisCacheManager.setCachePrefix(cachePrefix);
        // key缓存的过期时间, 600秒
        redisCacheManager.setDefaultExpiration(600L);
        return redisCacheManager;

    }


}
